package com.charm.restaurant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.charm.restaurant.common.Result;
import com.charm.restaurant.entity.Feedback;
import com.charm.restaurant.entity.Order;
import com.charm.restaurant.mapper.FeedbackMapper;
import com.charm.restaurant.mapper.OrderMapper;
import com.charm.restaurant.service.FeedbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 评价反馈服务实现类
 */
@Slf4j
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 用户提交评价
     */
    @Override
    public Result<Feedback> submitFeedback(Feedback feedback) {
        // 模拟获取当前登录用户ID
        Long userId = 1L;
        feedback.setUserId(userId);

        // 验证订单是否存在且属于当前用户
        if (feedback.getOrderId() != null) {
            Order order = orderMapper.selectById(feedback.getOrderId());
            if (order == null) {
                return Result.error("订单不存在");
            }
            if (!order.getUserId().equals(userId)) {
                return Result.error("不能评价其他用户的订单");
            }
            feedback.setMerchantId(order.getMerchantId());
        }

        // 验证评分
        if (feedback.getRating() == null || feedback.getRating() < 1 || feedback.getRating() > 5) {
            return Result.error("评分必须在1-5之间");
        }

        // 保存评价
        this.save(feedback);

        return Result.success(feedback);
    }

    /**
     * 用户查询自己的评价
     */
    @Override
    public Result<Page<Feedback>> getUserFeedbacks(Long userId, int page, int pageSize) {
        try {
            if (userId == null) {
                userId = 1L; // 默认用户ID
            }
            log.info("查询用户ID={}的评价列表, page={}, pageSize={}", userId, page, pageSize);

            // 分页查询用户评价
            Page<Feedback> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<Feedback> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Feedback::getUserId, userId);
            queryWrapper.eq(Feedback::getDeleted, 0); // 确保只查询未删除的记录
            queryWrapper.orderByDesc(Feedback::getCreateTime);

            log.info("执行查询前的参数: userId={}, page={}, pageSize={}", userId, page, pageSize);
            Page<Feedback> feedbackPage = this.page(pageInfo, queryWrapper);
            log.info("查询结果: 总记录数={}, 当前页记录数={}",
                    feedbackPage.getTotal(), feedbackPage.getRecords().size());

            return Result.success(feedbackPage);
        } catch (Exception e) {
            log.error("查询用户评价列表出错", e);
            return Result.error("查询评价列表失败: " + e.getMessage());
        }
    }

    /**
     * 商家查询评价
     */
    @Override
    public Result<Page<Feedback>> getMerchantFeedbacks(int page, int pageSize) {
        // 模拟获取当前登录商家ID
        Long merchantId = 1L;

        // 分页查询商家评价
        Page<Feedback> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Feedback> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Feedback::getMerchantId, merchantId);
        queryWrapper.orderByDesc(Feedback::getCreateTime);
        Page<Feedback> feedbackPage = this.page(pageInfo, queryWrapper);

        return Result.success(feedbackPage);
    }

    /**
     * 商家回复评价
     */
    @Override
    public Result<Feedback> replyFeedback(Long id, String reply) {
        // 模拟获取当前登录商家ID
        Long merchantId = 1L;

        // 查询评价
        Feedback feedback = this.getById(id);
        if (feedback == null) {
            return Result.error("评价不存在");
        }

        // 验证评价是否属于当前商家
        if (!feedback.getMerchantId().equals(merchantId)) {
            return Result.error("不能回复其他商家的评价");
        }

        // 更新回复
        feedback.setReply(reply);
        feedback.setReplyTime(LocalDateTime.now());
        this.updateById(feedback);

        return Result.success(feedback);
    }

    /**
     * 根据ID查询评价详情
     */
    @Override
    public Result<Feedback> getFeedbackById(Long id) {
        Feedback feedback = this.getById(id);
        if (feedback == null) {
            return Result.error("评价不存在");
        }
        return Result.success(feedback);
    }

    /**
     * 删除评价
     */
    @Override
    public Result<String> deleteFeedback(Long id) {
        // 模拟获取当前登录用户ID
        Long userId = 1L;

        // 查询评价
        Feedback feedback = this.getById(id);
        if (feedback == null) {
            return Result.error("评价不存在");
        }

        // 验证评价是否属于当前用户
        if (!feedback.getUserId().equals(userId)) {
            return Result.error("不能删除其他用户的评价");
        }

        // 删除评价
        this.removeById(id);

        return Result.success("删除成功");
    }
}
